package com.molyfun.parents.activity.account;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.attachment.AttachmentView;
import com.molyfun.parents.fragment.dialog.CommonInputDialogFragment;
import com.molyfun.parents.fragment.dialog.DatePickerDialogFragment;
import com.molyfun.parents.fragment.dialog.SexChooseDialogFragment;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.GetMyPageResponse;
import com.molyfun.parents.rest.bean.MediaobjectBeanResponse;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.rest.bean.UpdateStudentInfoRequest;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.IDCardValidate;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.TimeUtils;
import com.molyfun.parents.view.common.MfEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/24/16.
 */
public class EditProfileActivity extends BaseChoosePicActivity implements View.OnClickListener{


    @InjectView(R.id.base_title_left)
    ImageView mBackBtn;
    @InjectView(R.id.card_num)
    MfEditText mUserCardNum;
    @InjectView(R.id.edit_name)
    MfEditText mName;
    @InjectView(R.id.birthday_choose)
    TextView mBirthdayChoose;
    @InjectView(R.id.sex_choose)
    TextView mSexChoose;

    @InjectView(R.id.report_list)
    AttachmentView mReportList;
    @InjectView(R.id.desc)
    TextView mDesc;
    @InjectView(R.id.desc_file_list)
    AttachmentView mDescFileList;
    @InjectView(R.id.submit)
    TextView mSubmit;
    @InjectView(R.id.base_title)
    TextView mTitle;

    ////0:男 1:女
    private String mSexStr = "0";

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, EditProfileActivity.class);
        context.startActivity(intent);
    }

    private int mCurrentMediaDataCallType = MediaDataCallType.ReportType;

    public static interface MediaDataCallType{
        int ReportType = 1001;
        int DescType = 1002;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        ButterKnife.inject(this);

        getSupportActionBar().setTitle("");

        mBackBtn.setOnClickListener(this);
        mBirthdayChoose.setOnClickListener(this);
        mSexChoose.setOnClickListener(this);
        mSubmit.setText("提交");
        mTitle.setText("学生信息");
        mTitle.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
        mTitle.getPaint().setStrokeWidth(1);
        mSubmit.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
        mSubmit.getPaint().setStrokeWidth(0.5f);
        mSubmit.setOnClickListener(this);
        mDesc.setOnClickListener(this);
        initData();

        mReportList.setAttachmentAddCallback(new AttachmentView.AttachmentAddCallback() {
            @Override
            public void onAttachmentAdd() {
                //报告素材
                //TODO 记录哪里添加素材
                chooseMedia();
                mCurrentMediaDataCallType = MediaDataCallType.ReportType;
            }
        });

        mDescFileList.setAttachmentAddCallback(new AttachmentView.AttachmentAddCallback() {
            @Override
            public void onAttachmentAdd() {
                //记录素材
                chooseMedia();
                mCurrentMediaDataCallType = MediaDataCallType.DescType;
            }
        });

        mReportList.setAttachmentDelCallback(new AttachmentView.AttachmentDelCallback() {
            @Override
            public void onAttachmentDel(MediaobjectlistBean mediaobjectlistBean) {
//                mCurrentMediaDataCallType = MediaDataCallType.ReportType;
                delStudentFile("dians", mediaobjectlistBean.getId());
            }
        });
        mDescFileList.setAttachmentDelCallback(new AttachmentView.AttachmentDelCallback() {
            @Override
            public void onAttachmentDel(MediaobjectlistBean mediaobjectlistBean) {
//                mCurrentMediaDataCallType = MediaDataCallType.DescType;
                delStudentFile("sdesc", mediaobjectlistBean.getId());
            }
        });

    }

    private void initData(){

        showProgressDialog();
        Call<GetMyPageResponse> call = MFPApplication.getInstance().getRestClient().getStudentInfo();
        call.enqueue(new Callback<GetMyPageResponse>() {
            @Override
            public void onResponse(Call<GetMyPageResponse> call, Response<GetMyPageResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null) {
                    GetMyPageResponse.MyPageBean myPageBean = response.body().getData();
                    mName.setText(myPageBean.getName());
                    mUserCardNum.setText(myPageBean.getCardid());
                    mBirthdayChoose.setText(TimeUtils.getDateByTimeMillis(myPageBean.getBirthdatetime()));
                    mReportList.addList(myPageBean.getDiagnosislist());
                    mDesc.setText(myPageBean.getSituationdescription());
                    mDescFileList.addList(myPageBean.getSituationdesclist());
                    if(myPageBean.getSex() == 0){
                        mSexStr = "0";
                        mSexChoose.setText("男");
                    }else{
                        mSexStr = "1";
                        mSexChoose.setText("女");
                    }
                }
            }

            @Override
            public void onFailure(Call<GetMyPageResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    private String mUserCardNumStr;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.submit:
                if(TextUtils.isEmpty(mName.getText().toString().trim())){
                    toast("请输入学生姓名");
                    return;
                }
                if(TextUtils.isEmpty(mBirthdayChoose.getText().toString().trim())){
                    toast("请输入学生出生日期");
                    return;
                }
                if(!TextUtils.isEmpty(mUserCardNum.getText().toString().trim())){
                    IDCardValidate.validate_effective(mUserCardNum.getText().toString().trim(), new IDCardValidate.CardValidateCallback() {
                        @Override
                        public void onSuccess(String cardNum) {
                            mUserCardNumStr = cardNum;
                        }

                        @Override
                        public void onError(String cardErrorMsg) {
                            mUserCardNumStr = null;
                            toast(cardErrorMsg);
                        }
                    });
                    if(TextUtils.isEmpty(mUserCardNumStr)){
                        return;
                    }
                }

                updateUserInfo(mName.getText().toString().trim(), mSexStr, mBirthdayChoose.getText().toString().trim(), mUserCardNum.getText().toString().trim(),
                        mDesc.getText().toString().trim());
                break;
            case R.id.base_title_left:
                finish();
                break;
            case R.id.desc:
                new CommonInputDialogFragment.CommonInputDialogBuilder(mDesc.getText().toString())
                        .setOnCommonInputCallback(new CommonInputDialogFragment.OnCommonInputCallback() {
                            @Override
                            public void onInputConfirm(String content) {
                                mDesc.setText(content);
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());
                break;
            case R.id.birthday_choose:

                TimeUtils.getChooseDate(EditProfileActivity.this, new DatePickerDialogFragment.IDateCallback() {
                    @Override
                    public void onTimeChoosed(String time) {
                        if(!TimeUtils.isAfterToday(time)){
                            mBirthdayChoose.setText(time);
                        }else{
                            toast("不能选择今后的日期");
                        }
                    }
                });

                break;
            case R.id.sex_choose:
                new SexChooseDialogFragment.SexChooseDialogBuilder()
                        .setSexChooseCallback(new SexChooseDialogFragment.SexChooseCallback() {
                            @Override
                            public void onSexChoose(boolean isMale) {
                                if(isMale){
                                    mSexStr = "0";
                                    mSexChoose.setText("男");
                                }else{
                                    mSexStr = "1";
                                    mSexChoose.setText("女");
                                }
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());
                break;
        }
    }

    @Override
    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        //TODO 上传到服务器
        if(!TextUtils.isEmpty(originalUrl)){
//            MediaobjectlistBean mediaobjectlistBean = new MediaobjectlistBean();
//            mediaobjectlistBean.setUrl(originalUrl);
//            mediaobjectlistBean.setType(1);
            if(mCurrentMediaDataCallType == MediaDataCallType.ReportType){
//                mReportList.addAttachment(mediaobjectlistBean);
                uploadStudentFile("dians", "1", "", originalUrl, "");
            }else{
//                mDescFileList.addAttachment(mediaobjectlistBean);
                uploadStudentFile("sdesc", "1", "", originalUrl, "");
            }
        }
    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        if(!TextUtils.isEmpty(path)){
//            MediaobjectlistBean mediaobjectlistBean = new MediaobjectlistBean();
//            mediaobjectlistBean.setUrl(path);
//            mediaobjectlistBean.setCover(cover);
//            mediaobjectlistBean.setType(2);
            if(mCurrentMediaDataCallType == MediaDataCallType.ReportType){
//                mReportList.addAttachment(mediaobjectlistBean);
                uploadStudentFile("dians", "2", cover, path, "");
            }else{
//                mDescFileList.addAttachment(mediaobjectlistBean);
                uploadStudentFile("sdesc", "2", cover, path, "");
            }
        }
    }

    @Override
    public String getAttachmentFolder() {
        return "studentInfo";
    }

    /**
     * @param filetype 分类 诊断文件:dians 问题描述文件:sdesc
     * @param type 类型 1:图片 2:视频 3:音频 5:文件
     * @param cover 视频封面
     * @param url 链接
     * @param name name
     * @return
     */
    private void uploadStudentFile(final String filetype,final String type,final String cover,
                                   final String url,final String name){
        Call<MediaobjectBeanResponse> call = MFPApplication.getInstance().getRestClient().uploadStudentFile(filetype, type, cover,
                url, name);
        call.enqueue(new Callback<MediaobjectBeanResponse>() {
            @Override
            public void onResponse(Call<MediaobjectBeanResponse> call, Response<MediaobjectBeanResponse> response) {
                if (response.body() != null) {
                    if(response.body().getCode() == 200 && response.body().getData() != null){
                        if(filetype.equals("dians")){
                            mReportList.addAttachment(response.body().getData());
                        }else{
                            mDescFileList.addAttachment(response.body().getData());
                        }
                        toast("上传成功");
                    }
                }
            }

            @Override
            public void onFailure(Call<MediaobjectBeanResponse> call, Throwable t) {
//                toast("更新失败");
            }
        });
    }

    private void delStudentFile(String filetype, String id){
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().delStudentFile(filetype, id);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (response.body() != null) {
                    if(response.body().getCode() == 200){
                        toast("删除成功");
                    }else{
                        toast(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
//                toast("更新失败");
            }
        });
    }

    private void updateUserInfo(String studentName, String sex, String birthday, String cardId, String situationdescription){
        UpdateStudentInfoRequest updateStudentInfoRequest = new UpdateStudentInfoRequest(studentName, sex, birthday, cardId, situationdescription );

        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().updateStudentInfo(updateStudentInfoRequest);
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.body() != null && response.body().getData() != null) {
                    if(response.body().getCode() == 200){
                        MFPApplication.getInstance().setUser(response.body().getData());
                        PreferencesStorageUtil.setUserBean(EditProfileActivity.this, GsonUtil.toJson(response.body().getData()));
//                        refreshUserView(response.body().getData());
                        toast("更新成功");
                        finish();
                    }else{
                        toast(response.body().getMsg());
                    }

                }else{
                    toast("更新失败");
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                toast("更新失败");
            }
        });
    }
}
